//
//  MKCustomAnnotationView.m
//  UILbrary
//
//  Created by mac on 17/4/7.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "MKCustomAnnotationView.h"
#import "MKCustomViewController.h"
#import "MKCustomAnnotation.h"
@interface MKCustomAnnotationView()
@property (nonatomic, strong) MKCustomViewController *customVC;
@property (nonatomic, strong) MKCustomAnnotation *customAnnotation;

/**
 *  手表响铃按钮
 */
@property (nonatomic, strong) UIButton *bellButton;
/**
 *  聊天按钮
 */
@property (nonatomic, strong) UIButton *chatButton;
/**
 *  定位按钮
 */
@property (nonatomic, strong) UIButton *locationButton;
/**
 *  sos按钮
 */
@property (nonatomic, strong) UIButton *sosButton;

@property (nonatomic, assign) NSInteger cout;

/**
 是否显示 bellButton chatButton locationButton sosButton
 */
@property (nonatomic, assign) BOOL isShowButtons;


@end
@implementation MKCustomAnnotationView

#pragma mark - init
- (instancetype)initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier]) {
        CGRect myFrame = self.frame;
        myFrame.size.width = 20;
        myFrame.size.height = 20;
        self.frame = myFrame;
        self.isShowButtons = YES;
        self.customAnnotation = annotation;
        _customVC = [[MKCustomViewController alloc] init];
        self.canShowCallout = NO;
        self.opaque = NO;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPopView)];

        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        [self addGestureRecognizer:tap];
        
       
        
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:self animated:animated];

    UIView *callOutView = self.customVC.view;
    
    if(selected){
        self.customVC.titleArr = @[self.customAnnotation.deviceName,
                                   self.customAnnotation.deviceBatteryLevel,
                                   self.customAnnotation.deviceStatue,
                                   self.customAnnotation.deviceSignalTime,
                                   self.customAnnotation.deviceLocationTime,
                                   self.customAnnotation.deviceAddress];
        CGRect callOutViewBounds = callOutView.bounds;
        CGRect selfBounds        = self.bounds;
        if (callOutViewBounds.origin.x == selfBounds.origin.x) {
            callOutViewBounds.size.height = 200;
            callOutViewBounds.size.width = 250;
            callOutViewBounds.origin.x -= (callOutViewBounds.size.width - selfBounds.size.width) * 0.5;
            callOutViewBounds.origin.y -= callOutViewBounds.size.height;
            callOutView.frame = callOutViewBounds;
        }
        [self addSubview:callOutView];
        return;
    }
    [callOutView removeFromSuperview];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    
    if (CGRectContainsPoint(self.bellButton.frame, point)) {
        return self.bellButton;
    }
    else if(CGRectContainsPoint(self.chatButton.frame, point)) {
        return self.chatButton;
    }else if(CGRectContainsPoint(self.locationButton.frame, point)) {
        return self.locationButton;
    } else if (CGRectContainsPoint(self.sosButton.frame, point)) {
        return self.sosButton;
    }
    
    if (self.selected) {
        if (CGRectContainsPoint(self.customVC.view.frame, point)) {
            event = nil;
            return self.customVC.backgroundButton;
        }
    }
    UIView *hitView = [super hitTest:point withEvent:event];
    return hitView;
}


#pragma mark - private methods

- (void)showPopView{
   
    if (self.isShowButtons) {
        self.isShowButtons = NO;
        CGFloat selfW = self.frame.size.width;
        CGFloat selfH = self.frame.size.width;
        CGFloat buttonSize = 35;
        
        NSLog(@"WWWWWWWWWWWWWWW============== %f %f\n\n\n\n",selfW,selfH);
        CGFloat radius = selfW + 40;
        
        CGFloat bellButtonX     = selfW/2.0 - radius;
        CGFloat bellButtonY     = selfH/2.0;
        self.bellButton.bounds = CGRectMake(0, 0, buttonSize, buttonSize);
        self.bellButton.center = CGPointMake(bellButtonX, bellButtonY);
        
        CGFloat chatButtonX     = selfW/2.0 -radius/2.0;
        CGFloat chatButtonY     = selfH/2.0 + sinf(M_PI_2/3)*radius;
        self.chatButton.bounds   = CGRectMake(0, 0, buttonSize, buttonSize);
        self.chatButton.center = CGPointMake(chatButtonX, chatButtonY);
        
        CGFloat locationButtonX = selfW/2.0 + radius/2.0;
        CGFloat locationButtonY = selfH/2.0 + sinf(M_PI_2/3)*radius;
        self.locationButton.frame = CGRectMake(0, 0, buttonSize, buttonSize);
        self.locationButton.center = CGPointMake(locationButtonX, locationButtonY);
        
        
        CGFloat sosButtonX      = selfW/2.0 + radius;
        CGFloat sosButtonY      = selfH/2.0;
        self.sosButton.frame    = CGRectMake(0, 0, buttonSize, buttonSize);
        self.sosButton.center   = CGPointMake(sosButtonX, sosButtonY);
        [self addSubview:self.bellButton];
        [self addSubview:self.chatButton];
        [self addSubview:self.locationButton];
        [self addSubview:self.sosButton];
        
    }else{
        self.isShowButtons = YES;
        [self.bellButton removeFromSuperview];
        [self.chatButton removeFromSuperview];
        [self.locationButton removeFromSuperview];
        [self.sosButton removeFromSuperview];
    }
}
#pragma mark - event response
- (void)bellButtonClick{
    NSLog(@"向铃 时间");
}

- (void)chatButtonClick{
    NSLog(@"聊天 事件");
}

- (void)locationButtonClick{
    NSLog(@"定位 事件");
}

- (void)sosButtonClick{
    NSLog(@"SOS 事件");
}

#pragma mark - lazy methods
- (UIButton *)bellButton{
    if (!_bellButton) {
        _bellButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setBackgroundImage:[UIImage imageNamed:@"ic_mute"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(bellButtonClick) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _bellButton;
}

- (UIButton *)chatButton{
    if (!_chatButton) {
        _chatButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setBackgroundImage:[UIImage imageNamed:@"ic_sen_voice"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(chatButtonClick) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _chatButton;
}

- (UIButton *)locationButton{
    if (!_locationButton) {
        _locationButton =  ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setBackgroundImage:[UIImage imageNamed:@"ic_loc"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(locationButtonClick) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _locationButton;
}

- (UIButton *)sosButton{
    if (!_sosButton) {
        _sosButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setBackgroundImage:[UIImage imageNamed:@"ic_sos"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(sosButtonClick) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _sosButton;
}


//
//- (void)bellWidth:(CGFloat)bellW chatWidth:(CGFloat)chatW locationWidth:(CGFloat)locationW sosOriginx:(CGFloat)sosW {
//
//
//    if (self.cout == 1) {
//        _bell = [UIButton buttonWithType:UIButtonTypeCustom];
//    
//        CGRect bellFrame        = CGRectMake(0, 0, 0, 0);
//        bellFrame.size.height   = 35;
//        bellFrame.size.width    = 35;
//        bellFrame.origin.y      = 35+45;
//        bellFrame.origin.x      = bellW;
//        _bell.frame             = bellFrame;
//        
//        UIImage *image1 = [UIImage imageNamed:@"ic_mute"];
//        [_bell setBackgroundImage:image1 forState:UIControlStateNormal];
//        [_bell addTarget:self action:@selector(bellClick) forControlEvents:UIControlEventTouchUpInside];
//        _bell.layer.cornerRadius = 17.5;
//        [self addSubview:_bell];
//        
//        _chat = [UIButton buttonWithType:UIButtonTypeCustom];
//        CGRect chatFrame = CGRectMake(0, 0, 0, 0);
//        chatFrame.origin.x      = chatW;
//        chatFrame.origin.y      = 35 + 70;
//        chatFrame.size.height   = 35;
//        chatFrame.size.width    = 35;
//        _chat.layer.cornerRadius = 17.5;
//        [_chat addTarget:self action:@selector(chatClick) forControlEvents:UIControlEventTouchUpInside];
//        UIImage *image2 = [UIImage imageNamed:@"ic_sen_voice"];
//        [_chat setBackgroundImage:image2 forState:UIControlStateNormal];
//        [self addSubview:_chat];
//        
//        _location = [UIButton buttonWithType:UIButtonTypeCustom];
//        CGRect locationFrame        = CGRectMake(0, 0, 0, 0);
//        locationFrame.origin.x      = locationW;
//        locationFrame.origin.y      = 35 + 70;
//        locationFrame.size.width        = 35;
//        locationFrame.size.height   = 35;
//       
//        _location.layer.cornerRadius = 17.5;
//        [_location addTarget:self action:@selector(locationClick) forControlEvents:UIControlEventTouchUpInside];
//        UIImage *image3 = [UIImage imageNamed:@"ic_loc"];
//        [_location setBackgroundImage:image3 forState:UIControlStateNormal];
//        [self addSubview:_location];
//        //
//        //        _bell.hidden = NO;
//        //        _chat.hidden = NO;
//        //        _location.hidden = NO;
//        _sos = [UIButton buttonWithType:UIButtonTypeCustom];
//        CGRect sosFrame         = CGRectMake(0, 0, 0, 0);
//        sosFrame.origin.x       = sosW;
//        sosFrame.origin.y       = _bell.frame.origin.y;
//        sosFrame.size.width     = 35;
//        sosFrame.size.height    = 35;
//           _sos.layer.cornerRadius = 17.5;
//        [_sos addTarget:self action:@selector(sosAlarm)
//       forControlEvents:UIControlEventTouchUpInside];
//        [_sos setBackgroundImage:[UIImage imageNamed:@"ic_sos"] forState:UIControlStateNormal];
//        [self addSubview:_sos];
//        
//        self.cout += 1;
//    }else if(self.cout == 2){
//        
//        [_bell removeFromSuperview];
//        [_chat removeFromSuperview];
//        [_location removeFromSuperview];
//        [_sos removeFromSuperview];
//        self.cout = 1;
//    }
//}

//- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
//        if (CGRectContainsPoint(self.bell.frame, point)) {
//            NSLog(@"aaaaaaa");
//            return YES;
//        }
//        else if(CGRectContainsPoint(self.chat.frame, point)) {
//            NSLog(@"bbbbbbb");
//            return YES;
//        }else if(CGRectContainsPoint(self.location.frame, point)) {
//            NSLog(@"zzzzzzzzz");
//            return YES;
//        }
//    return NO;
//}




#pragma mark - 手表响铃方法
- (void)sosAlarm {
//    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"请选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"SOS报警", @"取消SOS报警", nil];
    
//    [actionSheet showInView:self];
    
    //    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //    if ([[userDefaults objectForKey:@"SupportSOS"] isEqualToString:@"0"]) {
    //        [SVProgressHUD showInfoWithStatus:@"该设备不支持SOS短信下发"];
    //    } else if ([[userDefaults objectForKey:@"SupportSOS"] isEqualToString:@"1"]) {
    //        [[NSNotificationCenter defaultCenter] postNotificationName:SEND_MESSAGE_NOTIFICATION object:nil];
    //    }
}

- (void)bellClick{
    NSLog(@"bell=============");
    [self setRingDown];
}

#pragma mark - 聊天方法
- (void)chatClick{
    // 这里发出通知，在主界面接收通知跳转页面
//    [[NSNotificationCenter defaultCenter] postNotificationName:DRAW_PRESENT_NOTIFICATION  object:CHATVIEWCONTROLLER];
    NSLog(@"chat------------");
}
#pragma mark - 定位方法
- (void)locationClick{
    NSLog(@"location>>>>>>>>>>>>>>");
    [self setSendLocationCmd];
}

#pragma mark - 定位
- (void)setSendLocationCmd{
    
//    NSString *url = [NSString stringWithFormat:@"%@?mds=%@&method=SendLocationCmd&BabyId=%@",API_GETDATE,[[NSUserDefaults standardUserDefaults] objectForKey:@"mds"],[[NSUserDefaults standardUserDefaults] objectForKey:BABYID]];
//    NSLog(@"定位请求＝＝＝＝＝＝＝＝＝＝URL＝＝＝＝＝＝%@",url);
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    
//    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
//    [manager POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        if ([responseObject[@"errorCode"] intValue] == 200) {
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"LOCATIONORDER" object:@15];
//            //            [SVProgressHUD showWithStatus:@"指令下达成功，等待响应" maskType:SVProgressHUDMaskTypeClear];
//            [SVProgressHUD showSuccessWithStatus:@"指令下达成功，等待响应" maskType:SVProgressHUDMaskTypeClear];
//        }else{
//            [SVProgressHUD showErrorWithStatus:@"指令下达失败" maskType:SVProgressHUDMaskTypeClear];
//        }
//        NSLog(@"定位请求＝＝＝＝＝＝＝＝＝＝请求成功＝＝＝＝＝%@",responseObject);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//        NSLog(@"定位请求＝＝＝＝＝＝＝＝＝＝请求失败＝＝＝＝＝%@",error);
//    }];
}
#pragma mark - 响铃
- (void)setRingDown{
//    NSString *url = [NSString stringWithFormat:@"%@?mds=%@&method=SetRingDown&BabyId=%@",API_GETDATE,[[NSUserDefaults standardUserDefaults] objectForKey:@"mds"],[[NSUserDefaults standardUserDefaults] objectForKey:BABYID]];
//    NSLog(@"响铃请求＝＝＝＝＝＝＝＝＝＝URL＝＝＝＝＝＝%@",url);
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    
//    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
//    [manager POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        NSLog(@"响铃请求＝＝＝＝＝＝＝＝＝＝请求成功＝＝＝＝＝%@",responseObject);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//        NSLog(@"响铃请求＝＝＝＝＝＝＝＝＝＝请求失败＝＝＝＝＝%@",error);
//    }];
    
}

#pragma mark - actionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"buttonIndex = %ld", buttonIndex);
//    switch (buttonIndex) {
//        case 0: {
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否发送SOS报警短信(短信所产生的费用由运营商收取)" delegate:self cancelButtonTitle:nil otherButtonTitles:@"否", @"是", nil];
//            alertView.tag = SETSOSALERTVIEW;
//            [alertView show];
//        }
//            break;
//        case 1: {
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否取消SOS报警" delegate:self cancelButtonTitle:nil otherButtonTitles:@"否",@"是", nil];
//            alertView.tag = CANCLESOSALERTVIEW;
//            [alertView show];
//        }
//            break;
//        default:
//            break;
//    }
}

#pragma mark - alertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//    switch (alertView.tag) {
//        case SETSOSALERTVIEW: {
//            switch (buttonIndex) {
//                case 0:
//                    break;
//                case 1: {
//                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//                    if ([[userDefaults objectForKey:@"SupportSOS"] isEqualToString:@"0"]) {
//                        [SVProgressHUD showInfoWithStatus:@"该设备不支持SOS短信下发"];
//                    } else if ([[userDefaults objectForKey:@"SupportSOS"] isEqualToString:@"1"]) {
//                        [[NSNotificationCenter defaultCenter] postNotificationName:SEND_MESSAGE_NOTIFICATION object:nil];
//                    }
//                }
//                default:
//                    break;
//            }
//        }
//            break;
//        case CANCLESOSALERTVIEW: {
//            switch (buttonIndex) {
//                case 0:
//                    break;
//                case 1: {
//                    //发送取消指令
//                    [SVProgressHUD showWithStatus:@"请稍后..."];
//                    [PWNetworking cancleSosAlarmWithMacid:[[NSUserDefaults standardUserDefaults] objectForKey:BABYMACID] complete:^(NSDictionary *returnObject, PWNetworkingRequestStatus status) {
//                        switch (status) {
//                            case PWNetworkingRequestStatusRequestSuccess: {
//                                [SVProgressHUD showSuccessWithStatus:@"取消成功"];
//                            }
//                                break;
//                                
//                            default: [SVProgressHUD showSuccessWithStatus:@"取消失败"];
//                                break;
//                        }
//                    }];
//                }
//                default:
//                    break;
//            }
//        }
//            break;
//        default:
//            break;
//    }
}


@end
